﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Roton.Video
{
    class CharacterGenerator
    {
        private int area;
        private Int32[][] backgroundMasks = new Int32[256][];
        private Int32[][] foregroundMasks = new Int32[256][];
        private Int32[] palette = new Int32[16];

        /// <summary>
        /// Create a character generator using the specified glyph data and palette.
        /// </summary>
        /// <param name="glyphData">Glyphs to use.</param>
        /// <param name="palette">Colors to use.</param>
        public CharacterGenerator(byte[] glyphData, Color[] palette)
        {
            GlyphSet glyphs = new GlyphSet(glyphData);
            area = glyphs.Width * glyphs.Height;

            // get glyph masks
            for (int i = 0; i < 256; i++)
            {
                foregroundMasks[i] = glyphs.GetGlyphForegroundMask(i);
                backgroundMasks[i] = glyphs.GetGlyphBackgroundMask(i);
            }

            // get palette values
            for (int i = 0; i < 16; i++)
            {
                this.palette[i] = palette[i].ToArgb();
            }
        }

        /// <summary>
        /// Render a character. The upper four bits of the color are used for the background color. The lower four bits of the color are used for the foreground color.
        /// </summary>
        /// <param name="ac"></param>
        /// <returns></returns>
        public Int32[] Render(AnsiChar ac)
        {
            Int32 backColor = palette[(ac.Color & 0xF0) >> 4];
            Int32[] backMask = backgroundMasks[ac.Character];
            Int32 foreColor = palette[ac.Color & 0xF];
            Int32[] foreMask = foregroundMasks[ac.Character];
            Int32[] result = new Int32[area];

            for (int i = 0; i < area; i++)
                result[i] = (foreMask[i] & foreColor) | (backMask[i] & backColor);

            return result;
        }
    }
}
